package com.wolfpire.system.common.util;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * web常用函数
 * 
 * @author lihd
 *
 */
public class RequestUtils {
	
	public static final Logger LOGGER = Logger.getLogger(RequestUtils.class);
	
	/**
	 * 从请求中自动构造请求对象
	 * @param <T> 构造对象泛型类型
	 * @param clazz 
	 * @param request
	 * @return
	 */
	public static <T> T getRequestObj(Class<T> clazz, HttpServletRequest request){
        
		try{
			T instance = clazz.newInstance();
			
	        setInstanceProperty(instance, request);
	        
	        return instance;
		}catch(Exception e){
			LOGGER.error("自动构建请求对象出错",e);
		}
        
        return null;
    }   
	
	/**
	 * 从请求中自动构造请求对象
	 * @param <T> 构造对象泛型类型
	 * @param clazz 
	 * @param request
	 * @return
	 */
	public static void setInstanceProperty(Object instance, HttpServletRequest request){
        
		String fieldName = null, fieldValue = null;
		try{
	        @SuppressWarnings("rawtypes")
			Enumeration e = request.getParameterNames();   
	        
	        while (e.hasMoreElements()) {   
	            fieldName = (String) e.nextElement();          //名   
	            fieldValue = request.getParameter(fieldName);  //值   
	            
	            ReflectionUtils.setProperty(instance, fieldName, fieldValue);
	        }
		}catch(Exception e){

			LOGGER.error("设置对象属性出错, fieldName="+fieldName+", fieldValue:"+fieldValue, e);
		}
    }   
	
	public <T> T getParameter(String name, Class<T> clazz, HttpServletRequest request){
		
		
		
		return null;
		
	}


	/**
	 * 获取指定名字的参数值
	 * 若参数值为空则返回null
	 * @param paramName 参数名
	 * @param request
	 * @return
	 */
	public static String getString(String paramName, HttpServletRequest request) {
		String temp = request.getParameter(paramName);
		if (StringUtils.isNotBlank(temp)) {
			return temp;
		} else {
			return null;
		}
	}

	/**
	 * 获取指定名字的参数值
	 * 若参数值为空则返回默认值
	 * @param paramName 参数名
	 * @param defaultString
	 * @param request 默认值
	 * @return
	 */
	public static String getString(String paramName, String defaultString,
			HttpServletRequest request) {
		String temp = getString(paramName, request);
		if (StringUtils.isBlank(temp)) {
			temp = defaultString;
		}
		return temp;
	}

	/**
	 * 获取指定名字的参数值，并转化为整形数字
	 * @param paramName
	 * @param request
	 * @return
	 */
	public static Integer getInt(String paramName, HttpServletRequest request) {
		String temp = request.getParameter(paramName);
		if(StringUtils.isNotBlank(temp)){
			return Integer.parseInt(temp.trim());
		}
		return null;
	}

	/**
	 * 获取指定名字的参数值，并转化为整形数字
	 * 若参数值为空或转化失败则返回默认值
	 * @param paramName
	 * @param request
	 * @return
	 */
	public static Double getDouble(String paramName, HttpServletRequest request) {
		try {
			String temp = getString(paramName, request);
			if (StringUtils.isNotBlank(temp)) {
				return Double.parseDouble(temp);
			}
		} catch (NumberFormatException e) {
			LOGGER.error("转化字符串为数字出错", e);
		}
		return null;
	}

	/**
	 * 获取指定名字的参数值，并转化为整形数字
	 * 若参数值为空或转化失败则返回默认值
	 * @param paramName
	 * @param defaultInt
	 * @param request
	 * @return
	 */
	public static Integer getInt(String paramName, int defaultInt, HttpServletRequest request) {
		try {
			String temp = getString(paramName, request);
			if (StringUtils.isNotBlank(temp)) {
				return Integer.parseInt(temp);
			}
		} catch (NumberFormatException e) {
			LOGGER.error("转化字符串为数字出错", e);
		}
		return defaultInt;
	}

	/**
	 * 获取指定名字的参数值，并转化为长整形数字
	 * @param paramName
	 * @param request
	 * @return
	 * @throws NumberFormatException
	 */
	public static Long getLong(String paramName, HttpServletRequest request) {
		
		String temp = request.getParameter(paramName);
		if(StringUtils.isNotBlank(temp)){
			return Long.parseLong(temp);
		}
		return null;

	}
	
	/**
	 * 返回指定名字的Double数组
	 * @param paramName
	 * @param request
	 * @return
	 * @throws NumberFormatException
	 */
	public static Double[] getDoubleArray(String paramName, HttpServletRequest request) {
		Double[] dbArray = null;

		String[] tempArray = request.getParameterValues(paramName);
		if(tempArray != null && tempArray.length > 0){
			int lengh = tempArray.length;
			dbArray = new Double[lengh];
			for(int i = 0; i < lengh; i ++){
				try {
					dbArray[i] = Double.parseDouble(tempArray[i]);
				} catch (Exception e) {
					dbArray[i] = null;
				}
			}
		}
		return dbArray;
	}
	
	public static BigDecimal[] getBigDecimalArray(String paramName, HttpServletRequest request) {
		BigDecimal[] bdArray = null;

		String[] tempArray = request.getParameterValues(paramName);
		if(tempArray != null && tempArray.length > 0){
			int lengh = tempArray.length;
			bdArray = new BigDecimal[lengh];
			for(int i = 0; i < lengh; i ++){
				try {
					bdArray[i] = new BigDecimal(tempArray[i]);
				} catch (Exception e) {
					bdArray[i] = null;
				}
			}
		}
		return bdArray;
	}
	

	/**
	 * 获取指定名字的参数值，并转化为长整形数字
	 * 若参数值为空或转化失败则返回默认值
	 * @param paramName
	 * @param defaultInt
	 * @param request
	 * @return
	 */
	public static Long getLong(String paramName, long defaultLong, HttpServletRequest request) {
		try {
			String temp = getString(paramName, request);
			if (StringUtils.isNotBlank(temp)) {
				return Long.parseLong(temp);
			}
		} catch (NumberFormatException e) {
			LOGGER.error("转化字符串为数字出错", e);
		}
		return defaultLong;
	}
	
	/**
	 * 返回指定名字的整形数组
	 * @param paramName
	 * @param request
	 * @return
	 * @throws NumberFormatException
	 */
	public static Integer[] getIntArray(String paramName, HttpServletRequest request) throws NumberFormatException {
		Integer[] intArray = null;

		String[] tempArray = request.getParameterValues(paramName);
		if(tempArray != null && tempArray.length > 0){
			int lengh = tempArray.length;
			intArray = new Integer[lengh];
			for(int i = 0; i < lengh; i ++){
				try {
					intArray[i] = Integer.valueOf(tempArray[i]);
				} catch (Exception e) {
					intArray[i] = null;
				}
			}
		}
		return intArray;
	}
	
	/**
	 * 返回指定名字的字符数组
	 * @param paramName
	 * @param request
	 * @return
	 * @throws NumberFormatException
	 */
	public static String[] getStringArray(String paramName, HttpServletRequest request) throws NumberFormatException {

		return request.getParameterValues(paramName);
	}
	
	/**
	 * 返回指定名字的浮点型数组
	 * @param paramName
	 * @param request
	 * @return
	 * @throws NumberFormatException
	 */
	public static Float[] getFloatArray(String paramName, HttpServletRequest request) throws NumberFormatException {
		Float[] floatArray = null;

		String[] tempArray = request.getParameterValues(paramName);
		if(tempArray != null && tempArray.length > 0){
			int lengh = tempArray.length;
			floatArray = new Float[lengh];
			for(int i = 0; i < lengh; i ++){
				try {
					floatArray[i] = Float.valueOf(tempArray[i]);
				} catch (Exception e) {
					floatArray[i] = null;
				}
			}
		}
		return floatArray;
	}
	
	public static Integer[] getIntArrayBySplit(String paramName, String split, HttpServletRequest request){
		Integer[] intArray = null;
		
		String temp = getString(paramName, request);
		if(StringUtils.isNotBlank(temp)){
			String[] tempArray = temp.split(split);
			if(tempArray != null && tempArray.length > 0){
				int lengh = tempArray.length;
				intArray = new Integer[lengh];
				for(int i = 0; i < lengh; i ++){
					intArray[i] = Integer.valueOf(tempArray[i]);
				}
			}
		}
		
		return intArray;
	}
	
	/**
	 * 返回指定名字的长整形数组
	 * @param paramName
	 * @param request
	 * @return
	 * @throws NumberFormatException
	 */
	public static Long[] getLongArray(String paramName, HttpServletRequest request)throws NumberFormatException {
		Long[] longArray = null;
		String[] tempArray = request.getParameterValues(paramName);
		if(tempArray != null && tempArray.length > 0){
			int lengh = tempArray.length;
			longArray = new Long[lengh];
			for(int i = 0; i < lengh; i ++){
				longArray[i] = Long.valueOf(tempArray[i]);
			}
		}
		return longArray;
	}
	
	public static Long[] getLongArrayBySplit(String paramName, String split, HttpServletRequest request){
		Long[] longArray = null;
		
		String temp = getString(paramName, request);
		if(StringUtils.isNotBlank(temp)){
			String[] tempArray = temp.split(split);
			if(tempArray != null && tempArray.length > 0){
				int lengh = tempArray.length;
				longArray = new Long[lengh];
				for(int i = 0; i < lengh; i ++){
					longArray[i] = Long.valueOf(tempArray[i]);
				}
			}
		}
		
		return longArray;
	}
	
	public static Date getDate(String paramName, String format, HttpServletRequest request){
		
		String temp = getString(paramName, request);
		if(StringUtils.isNotBlank(temp)){
			DateFormat dateFormat = new SimpleDateFormat(format);
			try {
				return dateFormat.parse(temp);
			} catch (ParseException e) {
				LOGGER.warn(e);
				e.printStackTrace();
			}
		}
		
		return null;
		
	} 
	
	public static Date getDate(String paramName, HttpServletRequest request){
		
		return getDate(paramName, "yyyy-MM-dd", request);
		
	} 
	

	/*
	 * 在评论的时候为了防止用户提交带有恶意的脚本，可以先过滤HTML标签，过滤掉双引号，单引号，符号&，符号<，符号 @
	 */
	public static String htmlEncode(String str) {
		String temp = "";
		if (str == null && !"".equals(str))
			return "";
		temp = str.replace("<", "&lt;").replace(">", "&gt;");
		return temp;
	}

	public static String htmlDecode(String str) {
		String temp = "";
		if (str == null && !"".equals(str))
			return "";
		temp = str.replace("&lt;", "<").replace("&gt;", ">");
		return temp;
	}
	
	public static String getIpAddr(HttpServletRequest request) {     
        String ip = request.getHeader("x-forwarded-for");     
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
            ip = request.getHeader("Proxy-Client-IP");     
        }     
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
            ip = request.getHeader("WL-Proxy-Client-IP");     
        }     
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
            ip = request.getRemoteAddr();     
        }     
        return ip;     
    } 
}
